package com.un.ebs.core.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Component
public class HttpUtil {
    public static String get(String url) {
        try {
            HttpEntity httpEntity = HttpClients.createDefault().execute(new HttpGet(url)).getEntity();
            return httpEntity != null ? EntityUtils.toString(httpEntity, "utf-8") : null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public String post(String url, Map params, Map headers) {

        try {
            HttpPost httpPost = new HttpPost(url);
            if (headers != null) {
                for (Iterator iter = headers.keySet().iterator(); iter.hasNext(); ) {
                    String key = (String) iter.next();
                    String value = String.valueOf(headers.get(key));
                    httpPost.setHeader(key, value);
                }
            }
            if (params != null) {
                List<NameValuePair> list = new ArrayList<NameValuePair>();
                for (Iterator iter2 = params.keySet().iterator(); iter2.hasNext(); ) {
                    String key2 = (String) iter2.next();
                    String value2 = String.valueOf(params.get(key2));
                    list.add(new BasicNameValuePair(key2, value2));
                }
                if (list.size() > 0) {
                    httpPost.setEntity(new UrlEncodedFormEntity(list));
                }
            }
            HttpEntity httpEntity = HttpClients.createDefault().execute(httpPost).getEntity();
            return httpEntity != null ? EntityUtils.toString(httpEntity, "utf-8") : null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}
